import logging
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent

LOG_DIR = BASE_DIR / 'logs'

if not os.path.isdir(LOG_DIR):
    os.makedirs(LOG_DIR)

# https://www.cnblogs.com/chenxuming/articles/9529128.html
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            #  {pathname} {funcName} {lineno}
            'format': '{levelname} {asctime} {hostname} {message}',
            'style': '{',
            'class': 'XUEKE.logging_helpers.HostnameAddingFormatter'
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'nplusone': {  # n+1 问题
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_DIR / 'nplusone.log',
            'maxBytes': 1024 * 1024 * 10,  # 日志大小 10M
            'backupCount': 2,  # 备份数为 2
            'formatter': 'simple'
        },
        'request_err': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOG_DIR / 'request_err.log',
            'maxBytes': 1024 * 1024 * 10,  # 日志大小 10M
            'backupCount': 2,  # 备份数为 2
            'formatter': 'simple',
            'encoding': 'utf-8',
        },
        'event': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': LOG_DIR / 'event.log',
            'when': 'midnight',
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        '': {
            'handlers': ['console'],
            'propagate': True,
        },
        'django.request': {
            'level': 'ERROR',
            'propagate': False,
        },
        'nplusone': {
            'handlers': ['nplusone'],
            'level': 'DEBUG',
        },
        'request_err': {
            'handlers': ['request_err'],
            'level': 'ERROR',
        },
        'event': {
            'handlers': ['console', 'event'],
            'level': 'INFO'
        },
    }
}


class LogstashLogger:
    logger_name = None

    def __init__(self):
        self.logger = logging.getLogger(self.logger_name)

    def info(self, *args, **kwargs):
        pass


class BaseLogger(LogstashLogger):
    logger_name = 'event'

    def info(self, class_fun, *args):
        self.logger.info(f"{class_fun} {' '.join(['%s'] * len(args))}", *args)


logger_info = BaseLogger()
